package com.zeratul.common.i18n.config;

import com.zeratul.common.i18n.config.prop.I18nProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

@AutoConfiguration(before = MessageSourceAutoConfiguration.class)
@ConditionalOnProperty(prefix = "i18n.config", name = "enabled", havingValue = "true", matchIfMissing = true)
@Slf4j
public class I18nLocalMessageSourceConfiguration {

    @Autowired
    private I18nProperties i18NProperties;

    /**
     * 通过本地配置文件加载MessageSource
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public MessageSource messageSource() {
        I18nProperties.Local local = i18NProperties.getLocal();
        log.debug("【国际化】基于Local的语言配置模式加载：{}", local);
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        // 注意这里不包含后缀，Spring会自动查找对应语言的文件
        messageSource.setBasename(local.getLoadName());
        messageSource.setDefaultEncoding(local.getEncoding());
        return messageSource;
    }
}
